import { defineStore } from "pinia";
import { ref } from "vue";

let chatListStore = defineStore('chatList', () => {
  let chatList = ref([])
  if (localStorage.getItem('chatList')) {
    chatList.value = JSON.parse(localStorage.getItem('chatList'))
  }
  const addChat = (chatItem, type?: string) => {
    if (chatList.value.some(item => item.chatId === chatItem.chatId)) {
      chatList.value.forEach(e => {
        if (e.chatId === chatItem.chatId) {
          if (type !== 'inChat') {
            chatItem.unReadCount = e.unReadCount + 1
          } else {
            chatItem.unReadCount = e.unReadCount
          }
          chatList.value.splice(chatList.value.indexOf(e), 1, chatItem)
          localStorage.setItem('chatList', JSON.stringify(chatList.value))
        }
      })
    } else {
      chatItem.unReadCount = 0
      chatList.value.unshift(chatItem)
      localStorage.setItem('chatList', JSON.stringify(chatList.value))
    }
  }
  const updateChatItemUnReadCount = (chatId: string) => {
    chatList.value.forEach(e => {
      if (e.chatId === chatId) {
        e.unReadCount = 0
        localStorage.setItem('chatList', JSON.stringify(chatList.value))
      }
    })
  }
  return {
    chatList,
    addChat,
    updateChatItemUnReadCount
  }
})

export default chatListStore